package com.nativetalk.service.four.reserve;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.SystemConfig;
import com.nativetalk.bean.course.TsNtCourseInfoDetail;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.reserve.ScheduleList;
import com.nativetalk.bean.reserve.TdNtReserveInsert;
import com.nativetalk.bean.reserve.TdNtReserveTimeList;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.*;
import com.nativetalk.dto.RecentlyAppointmentResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by lizhun on 2016/11/1.
 * Modified by wangzheng on 2017/02/15
 */
@Service
public class FourReserveServiceImpl implements FourReserveService {
    private static Logger logger = Logger.getLogger(FourReserveServiceImpl.class);
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private TdNtReserveTimeDao tdNtReserveTimeDao;
    @Resource
    private TdNtLiveCourseHisDao tdNtLiveCourseHisDao;
    @Resource
    private TdNtTeachCourseDao tdNtTeachCourseDao;
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TsNtCourseInfoDao tsNtCourseInfoDao;
    @Resource
    private TdNtMembCourseDao tdNtMembCourseDao;
    @Resource
    private TdNtMembCourseSizeDao tdNtMembCourseSizeDao;

    @Override
    public RetInfo search(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":coursesearch:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtReserveInsert tdNtReserveInsert = tdNtReserveDao.findTdNtReserver(tdNtMember.getMemb_id());
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取列表成功");
            if (tdNtReserveInsert != null) {
                retInfo.setObj(0);
            } else {
                retInfo.setObj(1);
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findTeacherReserveTime(int tea_id, TdNtMember tdNtMember, int version, String client_type,TimeZone clientTimeZone) {
        String logInfo = this.getClass().getName() + ":findTeacherReserveTime:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, SystemConfig> systemConfigMap = (Map<String, SystemConfig>) MemcachedUtils.get(MemcachedKey.systemConfig);
            Map<String, Object> params = new HashMap<>();
            params.put("tea_id", tea_id);
            Map<String, Object> map = new HashMap<>();
            SystemConfig systemConfig = systemConfigMap.get("systemAppointmentTimeThreshold");
            int systemAppointmentTimeThreshold = Integer.parseInt(systemConfig.getValue());
            logger.info("\n\n\nsystemAppointmentTimeThreshold=" + systemAppointmentTimeThreshold + "\n\n\n");

            // 第二步：查询老师7天内可以预约的时间
            List<ScheduleList> scheduleListList = new ArrayList<>();

            //查询老师七天开课情况
            Date date = new Date(System.currentTimeMillis());
//            Date reserve_date = CommonUtil.addData(new Date(Long.valueOf(date)), i);
            params.put("reserve_date", date);
            params.put("time",systemAppointmentTimeThreshold);
            List<TdNtReserveTimeList> tdNtReserveTimeLists = tdNtReserveTimeDao.findTdNtReserveTimeList(params);
            Map<Date,Integer> stringIntegerMap = new HashMap<>();
            for(TdNtReserveTimeList tdNtReserveTimeList : tdNtReserveTimeLists){
                stringIntegerMap.put(tdNtReserveTimeList.getDate(),tdNtReserveTimeList.getIs_valid());
            }
            logger.info("老师可预约时间7天数据库的数据--》" + JsonUtil.toJson(stringIntegerMap));

            //获取包括今天的7天的预约信息
            for (int i = 0; i < 7; i++) {
                ScheduleList scheduleList = new ScheduleList();
                Date reserve_date = CommonUtil.addData(date, i);
                List<TdNtReserveTimeList> tdNtReserveTimes = GetTeacherUtil.getReserveTime(reserve_date,clientTimeZone);
                for(TdNtReserveTimeList tdNtReserveTimeList1 : tdNtReserveTimes){
                    if(stringIntegerMap.get(tdNtReserveTimeList1.getDate()) != null){
                        tdNtReserveTimeList1.setIs_valid(stringIntegerMap.get(tdNtReserveTimeList1.getDate()));
                    }
                }
                scheduleList.setSchedule_date(reserve_date);
                scheduleList.setSchedule_list(tdNtReserveTimes);
                scheduleListList.add(scheduleList);
            }
            map.put("weekReservetime",scheduleListList);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取数据成功");
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findTeacherReserveCourse(int tea_id, TdNtMember tdNtMember, String date, int version, String client_type) {
        String logInfo = this.getClass().getName() + ":findTeacherReserveTime:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = RetInfo.getSuccessInfo();
        try {
            Map<String, SystemConfig> systemConfigMap = (Map<String, SystemConfig>) MemcachedUtils.get(MemcachedKey.systemConfig);
            SystemConfig systemConfig = systemConfigMap.get("systemAppointmentTimeThreshold");
            int systemAppointmentTimeThreshold = Integer.parseInt(systemConfig.getValue());
            Map<String, Object> map = new HashMap<>();
            logger.info("memb_id = "+tdNtMember.getMemb_id()+"~~~~~~~~~~~tea_id = "+tea_id);
            List<TsNtCourseInfoDetail> tsNtCourseInfoDetailList = tsNtCourseInfoDao.findAllCourseStudentBuy(tdNtMember.getMemb_id(),tea_id);
            Integer count = tsNtCourseInfoDao.findAllTeacherOpenCourseTheWeek(tea_id,systemAppointmentTimeThreshold);
            Boolean is_vaild = false;
            Integer teacherCourseSize = 0;
            if (count > 0){
                is_vaild = true;
            }
            for (TsNtCourseInfoDetail tsNtCourseInfoDetail : tsNtCourseInfoDetailList){
                if (tsNtCourseInfoDetail.getState() == 1){
                    teacherCourseSize++;
                }
            }
            map.put("haveTime",is_vaild);//可以预约的课程列表（老师是否开时间）
            map.put("buyCouSize", tsNtCourseInfoDetailList.size());//购买的课程数
            map.put("canUseCouSize",teacherCourseSize); //学生与老师共有课程的交集（可约的课程数）
            map.put("courses", tsNtCourseInfoDetailList); // 可以预约的课程列表
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    public RecentlyAppointmentResponse findRecentlyAppointment(TdNtTeacherResult teacher) {
        RecentlyAppointmentResponse response = tdNtReserveDao.findRecentlyAppointment(teacher.getTea_id());
        return response;
    }
}
